package com.quick.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quick.mapper.SysUserRoleMapper;
import com.quick.service.ISysRoleService;
import com.quick.service.ISysUserRoleService;
import com.quick.sys.domain.pojo.SysUserRole;
import com.quick.sys.domain.vo.SysRoleVo;
import com.quick.sys.domain.vo.SysUserRoleVo;
import com.quick.util.Convert;
import com.quick.util.QuickTool;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class SysUserRoleServiceImpl implements ISysUserRoleService {

    private final SysUserRoleMapper sysUserRoleMapper;
    private final ISysRoleService sysRoleService;
    @Override
    public List<SysUserRoleVo> loadUserRole(Integer userId) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRole::getUserId,userId);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(queryWrapper);
        if(QuickTool.isNull(sysUserRoles)) {
        	return new ArrayList<SysUserRoleVo>();
        }
        List<Integer> roleIds = sysUserRoles.stream().map(sysUserRole -> sysUserRole.getRoleId()).distinct().collect(Collectors.toList());
        Map<Integer, SysRoleVo> roleMap = sysRoleService.loadRole(roleIds);
        List<SysUserRoleVo> sysUserRoleVos = Convert.convert(sysUserRoles,SysUserRoleVo.class);
        sysUserRoleVos.forEach(sysUserRoleVo -> {
            sysUserRoleVo.setRoleName(roleMap.get(sysUserRoleVo.getRoleId()).getName());
        });
        return Convert.convert(sysUserRoles,SysUserRoleVo.class);
    }
	@Override
	public void saveUserRole(List<Integer> roles, Integer userId) {
		QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
		queryWrapper.lambda().eq(SysUserRole::getUserId, userId);
		sysUserRoleMapper.delete(queryWrapper);
		for (Integer role : roles) {
			SysUserRole entity = new SysUserRole();
			entity.setUserId(userId);
			entity.setRoleId(role);
			sysUserRoleMapper.insert(entity);
		}
	}
}
